<?php

class EmbeddedOrganizationalUnitElectiveOfficesForm extends BaseForm
{
  
  /**
   * @var OrganizationalUnit
   */
  protected $unit;

  public function __construct (OrganizationalUnit $unit, $defaults = array(), $options = array(), $CSRFSecret = null)
  {
    $this->unit = $unit;
    $this->updateDefaultsFromObject();
    
    parent::__construct($defaults, $options, $CSRFSecret);
  }

  public function configure ()
  {
    $this->disableLocalCSRFProtection();
    
    $properties = $this->unit->getPropertyValuesByType(OrganizationalPropertyType::ELECTIVE_OFFICE);
    foreach ($properties as $property)
    {
      $this->widgetSchema[$property->getFormWidgetId()] = $property->getFormWidget();
      $this->widgetSchema[$property->getFormWidgetId()]->setLabel($property->getFormWidgetLabel());
      $this->validatorSchema[$property->getFormWidgetId()] = new sfValidatorPass(); // TODO No good
    }
    
    parent::configure();
  }

  public function save ($con = null)
  {
    $properties = $this->unit->getPropertyValuesByType(OrganizationalPropertyType::ELECTIVE_OFFICE);
    
    foreach ($properties as $property)
    {
      $oupa = OrganizationalUnitPropertyAssignmentTable::getInstance()->findByOrganizationalUnitAndOrganizationalProperty($this->unit, 
          $property->getProperty());
      
      if ($oupa->isNew())
      {
        $oupa->setOrganizationalUnitId($this->unit->getId());
        $oupa->setOrganizationalPropertyId($property->getProperty()
          ->getId());
      }
      $oupa->setValue($this->getValue($property->getFormWidgetId()));
      $oupa->save();
    }
  }

  protected function doBind (array $values)
  {
    return parent::doBind($values);
  }

  public function updateDefaultsFromObject ()
  {
    $properties = $this->unit->getPropertyValuesByType(OrganizationalPropertyType::ELECTIVE_OFFICE);
    foreach ($properties as $property)
    {
      $this->setDefault($property->getFormWidgetId(), $property->getValue());
    }
  }
}